package com.mxm.mirai.service;

import com.mxm.mirai.config.MXM_config;
import net.dreamlu.mica.http.HttpRequest;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.time.Duration;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ACGImgsService {

//    public static void main(String[] args) {
//        String url = getWallhavenImgSUrl();
//        System.out.println(url);
//        List<String> list = getWallhavenImgUrl(url);
//        for (String imgurl:list) {
//            System.out.println(imgurl);
//        }
//    }

    /**
     * 获取wallhaven.cc网中随机一图片
     * @return
     */
    public static String getWallhavenImgSUrl() {
        String html = HttpRequest.get("https://wallhaven.cc/search?q=id%3A1&sorting=random&ref=fp&seed=bubeJ&page=" + M_Random(1, 2311))
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
                .connectTimeout(Duration.ofSeconds(40))
                .execute()
                .asString();
        Matcher m = Pattern.compile("<a class=\"preview\"(.*?)href=\"(.*?)\"(.*?)target=").matcher(html);
        List<String> urls = new LinkedList<>();
        while (m.find()) {
            urls.add(m.group(2));
        }
        return urls.get(M_Random(0, urls.size()));
    }

    /**
     * 从wallhaven.cc网url中获取原图
     * @param url
     * @return
     */
    public static List<String> getWallhavenImgUrl(String url) {
        String html = HttpRequest.get(url).addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
                .connectTimeout(Duration.ofSeconds(40))
                .execute().asString();
        Matcher m = Pattern.compile("<div class=\"scrollbox\"><img id=\"wallpaper\" src=\"(.*?)\" alt=").matcher(html);
        List<String> urls = new LinkedList<>();
        while (m.find()) {
            //System.out.println(m.group(1));
            urls.add(m.group(1));
        }
        return urls;
    }

    /**
     * 获取Pictures网中随机一图片
     * @return
     */
    public static String getPicturesImgSUrl() {
        String html = HttpRequest.get("https://anime-pictures.net/pictures/view_posts/"+ M_Random(0, 6288)+"?lang=zh_CN")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
                .connectTimeout(Duration.ofSeconds(120))
                .execute()
                .asString();
        Matcher m = Pattern.compile("pubtime([\\s\\S]*?)<a href=\"(.*?)\"([\\s]*?)title=([\\s\\S]*?)>([\\s\\S]*?)<picture").matcher(html);
        List<String> urls = new LinkedList<>();
        while (m.find()) {
            urls.add(m.group(2));
        }
        //https://anime-pictures.net/pictures/view_post/667519?lang=zh_CN
        return "https://anime-pictures.net"+urls.get(M_Random(0, urls.size()));
    }
    /**
     * 从Pictures网url中获取原图
     * @param url
     * @return
     */
    public static List<String> getPicturesImgUrl(String url) {
        String html = HttpRequest.get(url).addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
                .connectTimeout(Duration.ofSeconds(120))
                .execute().asString();
        Matcher m = Pattern.compile("class=\"download_icon([\\s\\S]*?)href=\"(.*?)\"([\\s\\S]*?)title=\"下载图片\"").matcher(html);
        List<String> urls = new LinkedList<>();
        while (m.find()) {
            //System.out.println(m.group(1));
            if(!"".equals(m.group(2))){
                urls.add("https://anime-pictures.net"+ m.group(2));
            }
        }
        return urls;
    }

    private static Integer M_Random(Integer min, Integer max) {
        Random rand = new Random();
        return rand.nextInt(max) + min;
    }

    /**
     * 正则获取内容(失败返回null)
     *
     * @param reg   正则
     * @param html  网页
     * @param group 获取正则上第几处内容
     * @param blank 是否清除空格
     * @return
     */
    public static String VideoMatcher(String reg, String html, Integer group, boolean blank) {
        Matcher m = Pattern.compile(reg).matcher(html);
        while (m.find()) {
            String text = m.group(group);
            if (text == null || "".equals(text)) {
                return null;
            }
            if (blank) {
                return text.replace(" ", "").replaceAll(" ", "");
            }
            return text;
        }
        return null;
    }
    /**
     * 访问URL获取File流
     * @param urlPath 请求URL
     * @return
     */
    public static InputStream getURLFile(String urlPath) {
        try {
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类，抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            //设置超时
            httpURLConnection.setConnectTimeout(1000 * 50);
            //设置UA
            httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
            // 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）。
            httpURLConnection.connect();
            return httpURLConnection.getInputStream();
        } catch (Exception e) {
            MXM_config.log.BotLog(null,"图片请求错误:"+urlPath,true);
            return null;
        }
    }
}
